<?php
declare(strict_types=1);

namespace App\Repository;

use Hyperf\DbConnection\Model\Model;

abstract class BaseRepository implements RepositoryInterface
{
    public function __construct(
        protected Model $model
    )
    {
    }

    public function find($id)
    {
        return $this->model->find($id);
    }

    public function findOneBy(array $criteria)
    {
        $query = $this->model->query();

        foreach ($criteria as $field => $value) {
            $query->where($field, $value);
        }

        return $query->first();
    }

    public function findAll(array $criteria = []): array
    {
        $query = $this->model->query();

        foreach ($criteria as $field => $value) {
            $query->where($field, $value);
        }

        return $query->get()->toArray();
    }

    public function create(array $data)
    {
        return $this->model->create($data);
    }

    public function update($id, array $data): bool
    {
        $model = $this->model->find($id);
        if (!$model) {
            return false;
        }
        return $model->update($data);
    }

    /**
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function delete($id): bool
    {
        $model = $this->model->find($id);
        if (!$model) {
            return false;
        }
        return $model->delete();
    }
    public function where(array $criteria = [])
    {
        $query = $this->model->query();

        foreach ($criteria as $field => $value) {
            $query->where($field, $value);
        }
        return $query;
    }
    public function paginate(int $page = 1, int $perPage = 15): array
    {
        return $this->model->paginate($perPage, ['*'], 'page', $page)->toArray();
    }
}